<template>

  <div>
    <!--新增区域-->
    <div class="iRight">
      <el-button type="primary" @click="add">新增</el-button>
    </div>

    <!--搜索区域-->
    <div style="margin: 10px 0">
      <el-input v-model="search" style="width: 20%" placeholder="输入关键字搜索" clearable/>
      <el-button type="primary" style="margin-left: 5px" @click="load">查询</el-button>
    </div>


    <!--用户列表-->
    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column label="头像" width="100px">
        <template #default="scope">
          <el-image
              style="width: 50px; height: 50px;border-radius: 4px"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column property="username" label="用户名" width="120px"></el-table-column>
      <el-table-column property="sex" label="性别"></el-table-column>


      <el-table-column property="email" label="邮箱"></el-table-column>
      <el-table-column property="createdTime" label="创建时间"></el-table-column>
      <el-table-column property="lastLogin" label="最近登录"></el-table-column>
      <el-table-column label="角色">
        <template #default="scope">
          <span v-if="scope.row.role === 1">管理员</span>
          <span v-if="scope.row.role === 0">普通用户</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
              @click="handleEdit(scope.row)">编辑
          </el-button>
          <el-popconfirm title="确认删除吗？" hide-icon @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--新增弹框-->
    <el-dialog v-model="dialogVisible" width="40%">

      <el-form :model="form" :label-position="labelPosition" label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="form.sex" style="width: 80%"></el-input>
        </el-form-item>
        <!--        <el-form-item label="头像">-->
        <!--          <el-input v-model="form.avatar" style="width: 80%"></el-input>-->
        <!--        </el-form-item>-->

        <!--头像上传-->
        <el-upload
            class="avatar-uploader"
            :action="filesUploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <el-form-item label="邮箱">
          <el-input v-model="form.email" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="form.createdTime" value-format="YYYY-MM-DD" type="date" style="width: 80%"
                          clearable></el-date-picker>
        </el-form-item>
        <el-form-item label="最近登录">
          <el-date-picker v-model="form.lastLogin" value-format="YYYY-MM-DD" type="date" style="width: 80%"
                          clearable></el-date-picker>
        </el-form-item>
      </el-form>


      <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </span>
      </template>
    </el-dialog>


    <!--分页脚标-->
    <div class="iRight">
      <el-pagination
          :total="total" :current-page="currentPage"
          background layout="prev, pager, next"
          @current-change="handleCurrentChange">
      </el-pagination>
    </div>


  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "User",
  components: {},

  data() {
    return {
      form: {},
      dialogVisible: false,
      search: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      labelPosition: 'left',
      imgURl: '',
      filesUploadUrl: "http://" + window.server.filesUploadUrl + ":9090/files/upload"
    }
  },

  created() {
    this.load()
  },

  methods: {
    //编辑
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },
    //删除
    handleDelete(id) {
      console.log(id);
      request.delete("/user/" + id).then(res => {
        if (res.code === '0') {
          this.$message({
            type: "success",
            message: "删除成功"
          })
        } else {
          this.$message({
            type: "error",
            message: res.msg
          })
        }
        this.load() //删除完成之后刷新表格数据
      })
    },
    //改变当前页
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.load()
    },
    //新增
    add() {
      this.dialogVisible = true
      this.form = {}
    },
    //保存
    save() {
      if (this.form.id) {
        //有id则更新
        request.put("/user", this.form).then(res => {
          console.log(res)
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "更新成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load() //更新完成之后刷新表格数据
          this.dialogVisible = false //并且关闭弹窗
        })
      } else {
        //没有id则新增
        request.post("/user", this.form).then(res => {
          console.log(res)
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "新增成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load() //新增完成之后刷新表格数据
          this.dialogVisible = false //并且关闭弹窗
        })
      }
    },

    //查询
    load() {
      request.get("/user", {
        params: {
          pageNum: this.currentPage,
          search: this.search,
        }
      }).then(res => {
        console.log(res)
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },

    //头像上传
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.form.avatar = res.data;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
  }
}
</script>

<style scoped>
/*.iRight {*/
/*  margin: 10px 0;*/
/*  position: absolute;*/
/*  right: 10px;*/
/*  text-align: center;*/
/*}*/

/*头像上传*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>